<template>
  <h2>{{ pageTitle }}</h2>
  <el-row justify="space-between" :gutter="20">
    <el-col :span="12">
      <el-row justify="start">
        <el-input v-model="search" placeholder="搜索客户姓名" clearable :prefix-icon="SearchIcon">
          <template #append>
            <el-button :icon="RefreshRight" @click="refreshData" circle :loading="isDownloading"/>
          </template>
        </el-input>
      </el-row>
    </el-col>
    <el-col :span="8">
      <el-row justify="end">
        <template v-if="isCheckable && !selectDeletion">
          <el-button text>效率模式</el-button>
          <el-switch v-model="efficiencyMode" inline-prompt active-text="开" inactive-text="关"  style="padding-right: 20px"/>
        </template>
        <template v-if="isModifiable">
          <template v-if="selectDeletion">
            <el-button type="default" @click="selectDeletion = false">取消</el-button>
            <el-button type="danger" @click="sureDeleteBooking">确定删除</el-button>
          </template>
          <template v-else>
            <el-button type="primary" :icon="Plus" @click="startCreateBooking">新建</el-button>
            <el-button type="danger" :icon="Delete" @click="startDeleteBooking">删除</el-button>
          </template>
        </template>
      </el-row>
    </el-col>
  </el-row>

  <el-table :data="bookingListFilter" :default-sort="{prop:'booking.bnum',order:'ascending'}"
            @selection-change="handleSelectionChange" stripe>
    <el-table-column type="selection" v-if="selectDeletion"/>
    <el-table-column fixed prop="booking.bnum" label="货单号" sortable/>
    <el-table-column prop="cfrom.name" label="发货客户" sortable/>
    <el-table-column prop="cto.name" label="收货客户" sortable/>
    <el-table-column prop="wfrom.name" label="发货仓" sortable/>
    <el-table-column prop="wto.name" label="收货仓" sortable/>
    <el-table-column prop="booking.money" label="运费" sortable/>
    <el-table-column prop="status" label="状态" sortable
                     :filters="BookingStatusFilters" :filter-method="filterHandler" filter-placement="bottom-end">
      <template #default="scope">
        <el-tag :type="chooseTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作">
      <template #default="scope">
        <el-button v-if="isViewable" link type="primary" size="small" @click="showDetails(scope.row)">详情</el-button>
        <el-button v-if="isCheckable" link type="primary" size="small" @click="startCheckOut(scope.row)"
                   :disabled="scope.row.status!=='等待签收'">签收
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="createDialogVisible" title="创建货单" :before-close="handleCreateResult">
    <BookingCheckIn :callback="handleCreateResult"/>
  </el-dialog>

  <BookingView v-if="bookingData!==undefined" :booking-data="bookingData" :close-dialog="()=>{bookingData=undefined}"/>
  <BookingCheckOut v-if="checkOutData!==undefined" :booking-data="checkOutData" :callback="handleCheckOutResult"/>

</template>

<script>
import {ref} from "vue";
import {BookingStatusFilters, chooseTagType, deleteBooking} from "@/scripts/data/booking";
import {Delete, Plus, RefreshRight, Search as SearchIcon} from "@element-plus/icons-vue";
import {ElNotification} from "element-plus";
import BookingCheckIn from "@/components/util/booking/BookingCheckIn";
import BookingView from "@/components/util/booking/BookingView";
import BookingCheckOut from "@/components/util/booking/BookingCheckOut";

export default {
  name: "BookingMain",
  props: ['pageTitle', 'isModifiable', 'isViewable', 'isCheckable', 'dataFetchMethod'],
  data() {
    return {
      isDownloading: true,
      bookingList: [],
      SearchIcon, Plus, Delete, RefreshRight,
      search: ref(''),
      selectDeletion: false,
      deleteList: [],
      bookingData: undefined,
      checkOutData: undefined,
      createDialogVisible: false,
      BookingStatusFilters,
      efficiencyMode: false,
    }
  },
  components: {
    BookingCheckOut,
    BookingView,
    BookingCheckIn
  },
  methods: {
    refreshData() {
      this.isDownloading = true;
      this.dataFetchMethod((data) => {
        this.bookingList = data;
        this.isDownloading = false;
      })
    },
    filterHandler(value, row) {
      return row.status === value;
    },
    startCreateBooking() {
      if (this.createDialogVisible) {
        ElNotification({
          title: '无法打开',
          message: '当前有任务正在进行',
          type: 'warning',
        });
      } else {
        this.createDialogVisible = true;
      }
    },
    handleCreateResult() {
      this.createDialogVisible = false;
      this.refreshData();
    },
    startDeleteBooking() {
      this.selectDeletion = !this.selectDeletion;
    },
    handleSelectionChange(val) {
      this.deleteList = val;
    },
    sureDeleteBooking() {
      // TODO 有时间改成批量执行的方式
      for (const item of this.deleteList) {
        deleteBooking(item.booking.bnum, (result) => {
          let ms = result ? '删除成功' : '删除失败'
          ElNotification({
            title: ms,
            message: '对货单号为' + item.booking.bnum + '的货单' + ms,
            type: result ? 'success' : 'error',
          });
          this.refreshData();
        })
      }
      this.selectDeletion = false;
    },
    showDetails(data) {
      this.bookingData = data;
    },
    startCheckOut(data) {
      if (this.checkOutData !== undefined) {
        ElNotification({
          title: '无法打开',
          message: '当前有任务正在进行',
          type: 'warning',
        });
      } else {
        this.checkOutData = data;
      }
    },
    handleCheckOutResult(result) {
      if (result == 1) {
        ElNotification({
          title: '验收成功',
          message: '货单验收成功',
          type: 'success',
        });
        this.refreshData();
      } else if (result == 0) {
        ElNotification({
          title: '验收失败',
          message: '货单验收失败',
          type: 'error',
        });
      }
      this.checkOutData = undefined;
    },
    chooseTagType
  },
  computed: {
    bookingListFilter() {
      return (this.search || this.efficiencyMode) ? this.bookingList.filter(
          (data) => (data.cfrom.name.includes(this.search) ||
              data.cto.name.includes(this.search)) && (!this.efficiencyMode || data.status === '等待签收')
      ) : this.bookingList;
    },
  },
  watch: {
    pageTitle() {
      this.refreshData()
    }
  },
  created() {
    this.refreshData()
  }
}
</script>

<style scoped>

</style>